﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Viettel.VOFFICE.DAO.DAL;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class FlowController : BaseController
    {
        /// <summary>
        /// Tạo luồng mới (thông tin cơ bản)
        /// </summary>
        /// <param name="flowModel"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("add_flow")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddFlow(FlowModel flowModel)
        {
            ITransaction transaction = null;
            try
            {
                var uow = new UnitOfWork();
                transaction = uow.BeginTransaction();
                List<ValidationResult> outError;
                if (flowModel.IsValid(out outError))
                {
                    var dbFlow = new Flow()
                        {
                            Name = flowModel.Name,
                            Description = flowModel.Description,
                            CreatedAt = DateTime.Now,
                            UpdatedAt = DateTime.Now,
                            IsActive = flowModel.IsActive,
                            IsCommon = flowModel.IsCommon,
                            DocTypeId = flowModel.IsCommon == true
                                        ? null
                                        : (flowModel.DocTypeId == 0 ? null : flowModel.DocTypeId),
                            IsReady = flowModel.IsReady,
                            IsDefault = flowModel.IsDefault,
                            DepartmentId = flowModel.DepartmentId == 0 ? null : flowModel.DepartmentId
                        };
                    //chỉ có 1 luồng duy nhất được chọn làm default
                    uow.FlowRepository.UniqueDefault(dbFlow.DocTypeId, dbFlow.DepartmentId);
                    uow.FlowRepository.Insert(dbFlow);
                    transaction.Commit();
                    return Json(SimplyResponse.ResposeWithId(dbFlow.Id));
                }
                else
                {
                    return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                        });
                }
            }
            catch (Exception)
            {
                if (transaction != null) transaction.Rollback();
                return Json(SimplyResponse.Response500());
                throw;
            }
            finally
            {
                if (transaction != null) transaction.Rollback();
            }
        }

        /// <summary>
        /// Cập nhập luồng
        /// </summary>
        /// <param name="flowModel"></param>
        /// <param name="modified"> </param>
        /// <returns></returns>
        [HttpPut]
        [ActionName("update_flow")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateFlow(FlowModel flowModel, string modified = "all")
        {
            ITransaction transaction = null;
            try
            {
                var uow = new UnitOfWork();
                transaction = uow.BeginTransaction();
                List<ValidationResult> outError;
                if (flowModel.IsValid(out outError))
                {
                    var dbFlow = uow.FlowRepository.GetById(flowModel.Id);
                    if (dbFlow != null)
                    {
                        if (modified == "all")
                        {
                            dbFlow.Name = flowModel.Name;
                            dbFlow.Description = flowModel.Description;
                            dbFlow.IsActive = flowModel.IsActive;
                            dbFlow.IsCommon = flowModel.IsCommon;
                            dbFlow.DocTypeId = flowModel.IsCommon == true
                                                   ? null
                                                   : (flowModel.DocTypeId == 0 ? null : flowModel.DocTypeId);
                            dbFlow.IsReady = flowModel.IsReady;
                            dbFlow.IsDefault = flowModel.IsDefault;
                            dbFlow.DepartmentId = flowModel.DepartmentId == 0 ? null : flowModel.DepartmentId;
                            if (dbFlow.IsDefault == true)
                            {
                                uow.FlowRepository.UniqueDefault(dbFlow.DocTypeId, dbFlow.DepartmentId);
                            }
                        }
                        else if (modified == "IsCommon")
                        {
                            dbFlow.IsCommon = flowModel.IsCommon;
                        }
                        else if (modified == "DocTypeId")
                        {
                            dbFlow.IsCommon = flowModel.IsCommon;
                            dbFlow.DocTypeId = flowModel.DocTypeId;
                        }
                        else if (modified == "IsActive")
                        {
                            dbFlow.IsActive = flowModel.IsActive;
                        }
                        dbFlow.UpdatedAt = DateTime.Now;
                        uow.FlowRepository.Update(dbFlow);
                        transaction.Commit();
                        return Json(SimplyResponse.Response200());
                    }
                    else
                    {
                        return Json(new JsonResponse()
                            {
                                Status = false,
                                Result = Resources.Resources.ManageFlowNotFound
                            });
                    }
                }
                else
                {
                    return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                        });
                }
            }
            catch (Exception ex)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }
                return Json(SimplyResponse.Response500());
            }
            finally
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                }
            }
        }

        /// <summary>
        /// Lấy danh sách luồng
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("get_all_flows")]
        public JsonResult GetFlow(int pageSize = 0, int pageIndex = 0)
        {
            try
            {
                if (pageSize != 0 && pageIndex >= 0)
                {
                    var pagedList = unitOfWork.FlowRepository.GetWithPaging(pageIndex, pageSize);
                    return Json(new JsonResponse()
                                    {
                                        Status = true,
                                        Result = new
                                                     {
                                                         PageIndex = pagedList.PageIndex,
                                                         PageSize = pagedList.PageSize,
                                                         PageCount = pagedList.PageCount,
                                                         List = pagedList.Select(o => new FlowModel(o)).ToList()
                                                     }
                                    }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var items = unitOfWork.FlowRepository.Get();
                    return Json(new JsonResponse()
                                    {
                                        Status = true,
                                        Result = items.Select(o => new FlowModel(o)).ToList()
                                    }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception)
            {

                throw;
            }
            return Json(null);
        }

        /// <summary>
        /// Tìm kiếm luồng
        /// TODO: Thêm trường không dấu để tìm kiếm tốt hơn.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("search_flow")]
        public JsonResult SearchFlow(string key)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(key))
                {
                    var items = unitOfWork.FlowRepository.SearchFlow(key).Select(o => new FlowModel(o)).ToList();
                    return Json(new JsonResponse() { Status = true, Result = items }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                throw;
            }
        }

        /// <summary>
        /// xóa luồng, chỉ xóa được nếu luồng chưa sẵn sàng
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("delete_flow")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteFlow(int id)
        {
            try
            {
                unitOfWork.FlowRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }

        /// <summary>
        /// Lấy ra thông tin cơ bản của một luồng.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("get_one")]
        public JsonResult GetOne(int id)
        {
            try
            {
                var item = unitOfWork.FlowRepository.GetById(id);
                if (null != item)
                {
                    return Json(new JsonResponse() { Status = true, Result = new FlowModel(item) },
                                JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new JsonResponse() { Status = false, Result = Resources.Resources.ManageFlowNotFound },
                                JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                //throw;
            }
        }

    }
}
